import time

import schedule
import usb.util

outEndPoint = None

def findAll():
    for dev in usb.core.find(find_all=True):
        print(dev)

def findById():
    device = usb.core.find(idVendor=0x5131, idProduct=0x2019)
    print(str(type(device)) + ":" + str(device))
    # ENDPOINT 0x81: Interrupt IN
    # ENDPOINT 0x82: Interrupt IN
    # ENDPOINT 0x83: Interrupt IN
    # ENDPOINT 0x84: Interrupt IN
    # ENDPOINT 0x4: Interrupt OUT
    return device


def findOutEndpoint():
    device = usb.core.find(idVendor=0x5131, idProduct=0x2019)
    print(str(type(device)) + ":" + str(device))
    # ENDPOINT 0x81: Interrupt IN
    # ENDPOINT 0x82: Interrupt IN
    # ENDPOINT 0x83: Interrupt IN
    # ENDPOINT 0x84: Interrupt IN
    # ENDPOINT 0x4: Interrupt OUT

    configuration = device.get_active_configuration()
    print(str(type(configuration)) + ":" + str(configuration))

    # Iterate over all interfaces in this configuration
    for interface_number in range(configuration.bNumInterfaces):
        # Get the interface by its number
        interface = configuration[(interface_number, 0)]

        # Print interface details for demonstration
        print(f"Interface {interface_number}:")
        # print(f"\tNumber of endpoints: {len(interface)}")
        print(f"\tInterface class: {interface.bInterfaceClass}")
        print(f"\tInterface subclass: {interface.bInterfaceSubClass}")
        print(f"\tInterface protocol: {interface.bInterfaceProtocol}")

        # You can also iterate over the endpoints in this interface
        for endpoint in interface:
            print(f"\tEndpoint {endpoint.bEndpointAddress}:")
            print(
                f"\t\tDirection: {'IN' if usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_IN else 'OUT'}")
            print(f"\t\tAttributes: {endpoint.wMaxPacketSize} bytes")

            if usb.util.endpoint_direction(endpoint.bEndpointAddress) != usb.util.ENDPOINT_IN:
                outEndPoint = endpoint
                return endpoint

def deviceSendMessage(device, outendpoint,message):
    device.write(0x4, message)

# def deviceReciveMessage(device, endpoint):
    # devic

def task1():
    print("Task1")

if __name__ == '__main__':
    device = findById()
    outEndPoint = findOutEndpoint()
    print(outEndPoint)

    # if device.is_kernel_driver_active(0):
    #     device.detach_kernel_driver(0)

    message = b'\x01\x02\x03\x04'
    deviceSendMessage(device, outEndPoint, message)


    # schedule.every().day.at("10:00").do(task1())
    # schedule.every().day.at("11:20").do(task1())
    #
    # # while True:
    # #     schedule.run_pending()
    # #     time.sleep(1)